//
//  KLFindPasswordViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/4/19.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLFindPasswordViewController.h"
#import "HemaConst.h"
#import "IdentifierValidator.h"
#import "JRToast.h"
#import "KLHelp.h"
#import "KLFindPasswordDetailViewController.h"
#import "KLHttpAPI.h"

@interface KLFindPasswordViewController ()
{
    int seconds;
}
@property (nonatomic,strong) UITextField *phoneNumber;
@property (nonatomic,strong) UITextField *securityCode;
@property (nonatomic,strong) UILabel *sendCode;
@property (nonatomic,strong) UIButton *nextStep;
@property (nonatomic,strong) NSTimer *timer;
@end

@implementation KLFindPasswordViewController
#pragma mark -懒加载
-(UITextField *)phoneNumber{
    if(!_phoneNumber){
        _phoneNumber = [[UITextField alloc]initWithFrame:CGRectMake(30, 50, UI_View_Width-60, 30)];
        
        //设置键盘为数字输入键盘
        _phoneNumber.keyboardType = UIKeyboardTypeNumberPad;
        //是否设置边框以及是否可见
        [_phoneNumber.layer setMasksToBounds:YES];
        //设置边框圆角的弧度
        [_phoneNumber.layer setCornerRadius:6.0];
        //设置边框线的宽
        [_phoneNumber.layer setBorderWidth:0.5];
        [_phoneNumber.layer setBorderColor:[UIColor grayColor].CGColor];
        
        _phoneNumber.borderStyle = UITextBorderStyleRoundedRect;
        _phoneNumber.font = [UIFont systemFontOfSize:15];
    }
    return _phoneNumber;
}

-(UITextField *)securityCode{
    if(!_securityCode){
        _securityCode = [[UITextField alloc]initWithFrame:CGRectMake(30, 105, UI_View_Width-60, 30)];
        
        //设置键盘为数字输入键盘
        _securityCode.keyboardType = UIKeyboardTypeNumberPad;
        //是否设置边框以及是否可见
        [_securityCode.layer setMasksToBounds:YES];
        //设置边框圆角的弧度
        [_securityCode.layer setCornerRadius:6.0];
        //设置边框线的宽
        [_securityCode.layer setBorderWidth:0.5];
        [_securityCode.layer setBorderColor:[UIColor grayColor].CGColor];
        
        _securityCode.borderStyle = UITextBorderStyleRoundedRect;
        _securityCode.font = [UIFont systemFontOfSize:15];
    }
    return _securityCode;
}

-(UILabel *)sendCode{
    if(!_sendCode){
        _sendCode = [[UILabel alloc]initWithFrame:CGRectMake(UI_View_Width/2+30, 105, self.securityCode.frame.size.width/2-30, 30)];
        _sendCode.textAlignment = NSTextAlignmentCenter;
        [_sendCode setFont:[UIFont systemFontOfSize:15]];
        _sendCode.userInteractionEnabled = YES;
    }
    return _sendCode;
}

-(UIButton *)nextStep{
    if(!_nextStep){
        _nextStep = [[UIButton alloc]initWithFrame:CGRectMake(30, 200, UI_View_Width-60, 40)];
        [_nextStep setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextStep setBackgroundColor:[UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1]];
        _nextStep.layer.cornerRadius = 5;
    }
    return _nextStep;
}

#pragma mark -视图显示
-(void)viewWillAppear:(BOOL)animated{
    self.navigationItem.title = @"找回密码";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //左侧返回按钮
    UIButton *backbutton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 10, 20)];
    [backbutton setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backbutton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backbutton];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    seconds = 60;
    
    //输入手机号作为第一响应者
    [self.phoneNumber becomeFirstResponder];
    
    //对textfield做设置
    self.phoneNumber.placeholder = @"请输入手机号";
    self.securityCode.placeholder = @"请输入验证码";
    [self.view addSubview:self.phoneNumber];
    [self.view addSubview:self.securityCode];
    //对label做设置
    self.sendCode.text = @"发送验证码";
    self.sendCode.textColor = [UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1];
    self.sendCode.backgroundColor =  [UIColor colorWithRed:(float)255/255 green:(float)165/255 blue:(float)2/255 alpha:1];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [self.sendCode addGestureRecognizer:tap];
    [self.view addSubview:self.sendCode];
    //画分割线
    UIView *splitLine = [[UIView alloc]initWithFrame:CGRectMake(UI_View_Width/2+30, 105, 0.5, 30)];
    splitLine.backgroundColor = [UIColor grayColor];
    [self.view addSubview:splitLine];
    //下一步按钮
    [self.nextStep addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.nextStep];
    
}

#pragma mark -方法中的方法体
-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)tap:(id)tap{
    //发送验证码
    BOOL isPhoneNumber = [IdentifierValidator isValid:IdentifierTypePhone value:self.phoneNumber.text];
    if(isPhoneNumber == true){
        //请求验证码
        NSString *username = self.phoneNumber.text;
        NSLog(@"userName :%@",username);
        [KLHelp showHUDAddedTo:self.view title:@"请稍候..." details:nil animated:YES];
        [KLHttpAPI requestSecurityCodeWithUserName:username  type:@"3" completionHandler:^(NSString *responseString) {
            NSLog(@"请求正常返回:%@",responseString);
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            NSDictionary *dic = [KLHelp dictionaryWithJsonString:responseString];
            NSString *successStr = [dic objectForKey:@"success"];
            if(successStr.integerValue == 1){
                //启动定时器
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
                
                [JRToast showWithText:@"验证码已发送" bottomOffset:50 duration:1.5];
                self.sendCode.backgroundColor =  [UIColor lightGrayColor];
                self.sendCode.userInteractionEnabled = NO;
                [self.view endEditing:NO];
            }else{
                [JRToast showWithText:[dic objectForKey:@"msg"] bottomOffset:50 duration:1.5];
            }
        } errorHandler:^(NSString *error) {
            NSLog(@"请求错误;%@",error);
            [KLHelp hideAllHUDsForView:self.view animated:YES];
        }];
    
    }else{
        [JRToast showWithText:@"手机号格式有误" bottomOffset:50 duration:1.5];
    }
}

-(void)updateLabel{
    seconds--;
    if(seconds >= 0){
        NSMutableAttributedString *secondsStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%d秒后重发",seconds]];
        
        [secondsStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
        [secondsStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"American Typewriter" size:17] range:NSMakeRange(0, 2)];
        
        self.sendCode.attributedText = secondsStr;
    }else{
        self.sendCode.backgroundColor =  [UIColor colorWithRed:(float)255/255 green:(float)165/255 blue:(float)2/255 alpha:1];
        self.sendCode.userInteractionEnabled = YES;
        self.sendCode.text = @"发送验证码";
        seconds = 60;
        [self.timer invalidate];
    }
}

-(void)next:(id)nextBtn{
    [self.view endEditing:YES];
    if(self.phoneNumber.text.length == 0){
        [JRToast showWithText:@"手机号不能为空" bottomOffset:50 duration:1.5];
        return ;
    }
    if([IdentifierValidator isValid:IdentifierTypePhone value:self.phoneNumber.text] == false){
        [JRToast showWithText:@"手机号格式有误" bottomOffset:50 duration:1.5];
        return ;
    }
    
    [KLHelp showHUDAddedTo:self.view title:@"请稍候..." details:nil animated:YES];
    [KLHttpAPI requestCheckSecurityCodeWithUserName:self.phoneNumber.text securityCode:self.securityCode.text completionHandler:^(NSString *responseString) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSDictionary *resultDic = [KLHelp dictionaryWithJsonString:responseString];
        NSString *isSuccess = [resultDic objectForKey:@"success"];
        if(isSuccess.integerValue == 0){
            [KLHelp showTextHUDforView:self.view text:[resultDic objectForKey:@"msg"]];
        }else{
            //存储临时令牌
            NSArray *array = [resultDic objectForKey:@"infor"];
            NSDictionary *infoDic = array[0];
            NSString *temp_token = [infoDic objectForKey:@"temp_token"];
            NSLog(@"temp_token :%@",temp_token);
            [[NSUserDefaults standardUserDefaults] setObject:temp_token forKey:@"temp_token"];
            
            
            // 获取指定的Storyboard，name填写Storyboard的文件名
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            // 从Storyboard上按照identifier获取指定的界面（VC），identifier必须是唯一的
            KLFindPasswordDetailViewController *findPwdDetailVC = [storyboard instantiateViewControllerWithIdentifier:@"findPasswordDetailVC"];
            [self.navigationController pushViewController:findPwdDetailVC animated:YES];
        }
    } errorHandler:^(NSString *error) {
        NSLog(@"验证错误");
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [KLHelp showTextHUDforView:self.view text:@"验证码输入有误"];
    }];
}

#pragma mark -取消view的第一响应者身份
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end
